package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.DmcGuoKangClientMapper;
import com.csun.cmny.provider.dao.DmcGuoKangDeviceMapper;
import com.csun.cmny.provider.exceptions.DmcBizException;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.domain.DmcGuoKangClient;
import com.csun.cmny.provider.model.domain.DmcGuoKangDevice;
import com.csun.cmny.provider.model.dto.guokang.GuoKangClientQuery;
import com.csun.cmny.provider.model.vo.guokang.GuoKangClientVo;
import com.csun.cmny.provider.model.vo.guokang.GuoKangCsunSleepVo;
import com.csun.cmny.provider.model.vo.guokang.GuoKangReportVo;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.csun.cmny.provider.service.DmcGuoKangClientService;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-12-09 17:31
 * @Description:
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DmcGuoKangClientServiceImpl extends BaseService<DmcGuoKangClient>
        implements DmcGuoKangClientService {

    @Resource
    private DmcGuoKangClientMapper dmcGuoKangClientMapper;
    @Resource
    private DmcGuoKangDeviceMapper dmcGuoKangDeviceMapper;
    @Resource
    private DmcDeviceService dmcDeviceService;
    @Autowired
    private RestTemplate myRestTemplate;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * save dmc guo kang client
     *
     * @param dmcGuoKangClient
     * @param loginAuthDto
     *
     * @return the int.
     */
    @Override
    public Integer save(DmcGuoKangClient dmcGuoKangClient, LoginAuthDto loginAuthDto) {

        dmcGuoKangClient.setUpdateInfo(loginAuthDto);

        /**
         * 校验编号是否唯一
         */
        Long id = dmcGuoKangClient.getId();
        String clientNo = dmcGuoKangClient.getClientNo();

        Example example = new Example(DmcGuoKangClient.class);
        Example.Criteria criteria = example.createCriteria();

        if (id != null) {
            criteria.andNotEqualTo("id", id);
        }
        criteria.andEqualTo("clientNo", clientNo);

        int result = selectCountByExample(example);
        if (result > 0) {
            throw new DmcBizException(ErrorCodeEnum.DMC100620001);
        }

        if (dmcGuoKangClient.isNew()) {

            return dmcGuoKangClientMapper.insertSelective(dmcGuoKangClient);
        }

        return dmcGuoKangClientMapper.updateByPrimaryKeySelective(dmcGuoKangClient);
    }

    /**
     * 根据Id删除
     *
     * @param id
     * @return
     */
    @Override
    public Integer deleteById(Long id) {

        // 判断是否绑定
        DmcGuoKangDevice dmcGuoKangDevice = new DmcGuoKangDevice();
        dmcGuoKangDevice.setClientId(id);
        int count = dmcGuoKangDeviceMapper.selectCount(dmcGuoKangDevice);
        if (count > 0) {
            throw new DmcBizException(ErrorCodeEnum.DMC100620001);
        }

        return dmcGuoKangClientMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询列表 - 分页
     *
     * @param guoKangClientQuery
     *
     * @return
     */
    @Override
    public List<GuoKangClientVo> queryListWithPage(GuoKangClientQuery guoKangClientQuery) {

        PageHelper.startPage(guoKangClientQuery.getPageNum(), guoKangClientQuery.getPageSize());

        return dmcGuoKangClientMapper.queryListWithPage(guoKangClientQuery);
    }

    /**
     * 绑定
     *
     * @param dmcGuoKangDevice
     * @param loginAuthDto
     *
     * @return
     */
    @Override
    public Integer bind(DmcGuoKangDevice dmcGuoKangDevice, LoginAuthDto loginAuthDto) {

        DmcGuoKangDevice record = new DmcGuoKangDevice();
        record.setClientId(dmcGuoKangDevice.getClientId());
        int count = dmcGuoKangDeviceMapper.selectCount(record);
        if (count > 0) {
            throw new DmcBizException(ErrorCodeEnum.DMC100620001);
        }

        record = new DmcGuoKangDevice();
        record.setDeviceId(dmcGuoKangDevice.getDeviceId());
        count = dmcGuoKangDeviceMapper.selectCount(record);
        if (count > 0) {
            throw new DmcBizException(ErrorCodeEnum.DMC100620002);
        }

        DmcGuoKangClient dmcGuoKangClient = dmcGuoKangClientMapper.selectByPrimaryKey(dmcGuoKangDevice.getClientId());
        if (PublicUtil.isEmpty(dmcGuoKangClient)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100620003);
        }
        dmcGuoKangDevice.setClientNo(dmcGuoKangClient.getClientNo());

        DmcDevice dmcDevice = dmcDeviceService.selectByKey(dmcGuoKangDevice.getDeviceId());
        if (PublicUtil.isEmpty(dmcDevice)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100620004);
        }
        dmcGuoKangDevice.setDeviceNo(dmcDevice.getDeviceNo());

        return dmcGuoKangDeviceMapper.insertSelective(dmcGuoKangDevice);
    }

    /**
     * 解绑
     *
     * @param dmcGuoKangDevice
     * @return
     */
    @Override
    public Integer untied(DmcGuoKangDevice dmcGuoKangDevice) {

        return dmcGuoKangDeviceMapper.delete(dmcGuoKangDevice);
    }

    /**
     * 查询报表
     *
     * @param month
     *
     * @return
     */
    @Override
    public List<GuoKangReportVo> uploadSleepMonthReport(String month) {

        Map<String, Object> map = Maps.newHashMap();
        map.put("time", month);

        List<GuoKangReportVo> guoKangReportVoList = dmcGuoKangDeviceMapper.uploadSleepMonthReport(month);
        map.put("data", guoKangReportVoList);

        String result = JSONObject.fromObject(map).toString();

        String filePathPrefix = "G:\\report\\";
        String filePathPrefixRedis = (String) redisTemplate.opsForValue().get(RedisKeyUtil.getCsunSleepReportFilePrefix());
        if (PublicUtil.isNotEmpty(filePathPrefix)) {
            filePathPrefix = filePathPrefixRedis;
        }
        String filePath = filePathPrefix + "csun-sleep-" + month + ".json";
        String zipFilePath = filePathPrefix + "MS005-" + month + ".zip";
        log.info("============> filePath: {}", filePath);
        File file = new File(filePath);
        File zip = new File(zipFilePath);
        try {
            PrintStream ps = new PrintStream(new FileOutputStream(file));
            ps.println(result);
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        FileInputStream fis = null;

        try {
            fos = new FileOutputStream(zip);
            zos = new ZipOutputStream(fos);
            byte buffer[] = new byte[1024];            // 只是设置一个可以存放下你文件内容的大小 ，自己定义
            ZipEntry entry = new ZipEntry(file.getName());
            fis = new FileInputStream(file);
            zos.putNextEntry(entry);
            int read = 0;
            while ((read = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, read);
            }
        } catch (Exception e) {
            System.out.println("错误");
        } finally {                              //一定要关闭，否则丢失文件内容

            try {
                fis.close();
                zos.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        MultiValueMap mvm = new LinkedMultiValueMap();
        mvm.add("file", new FileSystemResource(zip));

        String url = "http://218.64.194.48:7780/products/mattress/MS005";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity httpEntity = new HttpEntity<>(mvm, headers); // 组装

        Object object = myRestTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        log.info(object.toString());

        return guoKangReportVoList;
    }

    /**
     * 查询未绑定的床垫
     *
     * @return
     */
    @Override
    public List<GuoKangCsunSleepVo> queryNotBindCsunSleepList() {

        return dmcGuoKangDeviceMapper.queryNotBindCsunSleepList();
    }

    @Override
    public String selectByDeviceNo(String deviceNo) {

        DmcGuoKangDevice dmcGuoKangDevice = new DmcGuoKangDevice();
        dmcGuoKangDevice.setDeviceNo(deviceNo);
        dmcGuoKangDevice = dmcGuoKangDeviceMapper.selectOne(dmcGuoKangDevice);
        if (PublicUtil.isNotEmpty(dmcGuoKangDevice)) {
            return dmcGuoKangDevice.getClientNo();
        }

        return null;
    }
}
